<!--
 * @Description: 维修估价
 * @Autor: 何兴家
 * @Date: 2020-10-27 15:24:15
 * @LastEditors: 马毅
 * @LastEditTime: 2021-12-27 17:31:32
-->
<template>
  <div style="background: #fff" v-loading="pageLoadingSwitch">
    <!-- 主信息表单 -->
    <FormPanel ref="mainOrderForm" :list="mainOrderFormList" :labelWidth="90" :isSubmitBtn="false"></FormPanel>

    <!-- 项目材料 -->
    <el-row :gutter="20">
      <el-col :span="16" :offset="0">
        <el-tabs v-model="activeDetailInfoTab" tab-position="top">
          <el-tab-pane label="维修项目" name="维修项目">
            <FilterTable
              ref="repairLabourTable"
              columnsRef="repair_repairReception_evalluation_repairLabourTable"
              height="auto"
              :columns="repairLabourColumns"
              :dataSource="repairLabourTableDataSource"
              :isMemoryPagination="true"
              selectionType="single"
              :onSyncTableData="handleSyncRepairLabourTableData"
              :onRowSelectChange="handleRepairLabourTableSelect"
              :onCellChange="handleRepairLabourTableCellChange"
              :onColumnsChange="columns => (this.repairLabourColumns = columns)"
            >
              <template slot="controls">
                <el-button size="small" type="primary" :disabled="tableBtnDisabled" icon="el-icon-plus" @click="handleAddRepairLabour">新增项目</el-button>
                <el-button size="small" type="primary" :disabled="tableBtnDisabled" icon="el-icon-plus" @click="handleAddRepairPart">新增配件</el-button>
                <el-button size="small" type="danger" :disabled="tableBtnDisabled" @click="handleDeleteRepairLabour">删除</el-button>
              </template>
            </FilterTable>
          </el-tab-pane>
          <el-tab-pane label="维修材料" name="维修材料">
            <FilterTable
              ref="repairPartTable"
              columnsRef="repair_repairReception_evalluation_repairPartTable"
              height="auto"
              :columns="repairPartColumns"
              :dataSource="repairPartTableDataSource"
              :isMemoryPagination="true"
              selectionType="single"
              :onSyncTableData="handleSyncRepairPartTableData"
              :onRowSelectChange="handleRepairPartTableSelect"
              :onCellChange="handleRepairPartTableCellChange"
              :onColumnsChange="columns => (this.repairPartColumns = columns)"
            >
              <template slot="controls">
                <el-button size="small" type="primary" :disabled="tableBtnDisabled" icon="el-icon-plus" @click="handleAddRepairPart">新增配件</el-button>
                <el-button size="small" type="danger" :disabled="tableBtnDisabled" @click="handleDeleteRepairPart">删除</el-button>
              </template>
            </FilterTable>
          </el-tab-pane>
          <el-tab-pane label="附加项目" name="附加项目">
            <FilterTable
              ref="additionItemTable"
              columnsRef="repair_repairReception_evalluation_additionItemTable"
              height="auto"
              :columns="additionItemColumns"
              :dataSource="additionItemTableDataSource"
              :isMemoryPagination="true"
              selectionType="single"
              :onSyncTableData="handleSyncAdditionItemTableData"
              :onRowSelectChange="handleAdditionItemTableSelect"
              :onCellChange="handleAdditionItemTableCellChange"
              :onColumnsChange="columns => (this.additionItemColumns = columns)"
            >
              <template slot="controls">
                <el-button size="small" type="primary" :disabled="tableBtnDisabled" icon="el-icon-plus" @click="handleAddAdditionItem">新增</el-button>
                <el-button size="small" type="danger" :disabled="tableBtnDisabled" @click="handleDeleteAdditionItem">删除</el-button>
              </template>
            </FilterTable>
          </el-tab-pane>
        </el-tabs>
      </el-col>
      <el-col :span="8" :offset="0">
        <FormPanel ref="ballanceForm" :list="ballanceFormList" :cols="1" :labelWidth="90" :isSubmitBtn="false"></FormPanel>
      </el-col>
    </el-row>

    <!-- 折扣率单独存放 -->
    <FormPanel ref="discountForm" :list="discountFormList" :labelWidth="90" :isSubmitBtn="false"></FormPanel>

    <el-row :gutter="20">
      <el-col :span="16" :offset="0">
        <el-row :gutter="20">
          <el-col :span="12" :offset="0">
            应收：
            <FormPanel ref="receivableForm" :list="receivableFormList" :cols="1" :labelWidth="90" :isSubmitBtn="false"></FormPanel>
          </el-col>
          <el-col :span="12" :offset="0">
            实收：
            <FormPanel ref="realIncomeForm" :list="realIncomeFormList" :cols="1" :labjkkjelWidth="90" :isSubmitBtn="false"></FormPanel>
          </el-col>
        </el-row>
        <ButtonArea style="justify-content: center">
          <el-button type="primary" :disabled="bottomBtnDisabledObj.create" @click="handleCreateNewOrderBtnClick">新增</el-button>
          <el-button type="primary" :disabled="bottomBtnDisabledObj.setMeal" @click="handleRepairSetMealBtnClick">维修套餐</el-button>
          <AjaxButton type="primary" :disabled="bottomBtnDisabledObj.save" :click="handleSave">保存</AjaxButton>
          <el-button type="primary" :disabled="bottomBtnDisabledObj.edit" @click="handleEditBtnClick">编辑</el-button>
          <el-button type="primary" @click="handleCancelBtnClick">取消</el-button>
        </ButtonArea>
        <ButtonArea style="justify-content: center">
          <el-button type="primary" :disabled="bottomBtnDisabledObj.cancellation" @click="handleDiscardRepairOrderClick">作废</el-button>
          <el-button type="primary" :disabled="bottomBtnDisabledObj.edit" @click="handleCreateRepairOrder">导出工单</el-button>
          <AjaxButton type="primary" :disabled="bottomBtnDisabledObj.printBallance" :click="handlePrintBallance">打印结算单</AjaxButton>
          <AjaxButton v-if="false" type="primary" :disabled="bottomBtnDisabledObj.printEvaluation" :click="handlePrintRepairOrder">打印估价单</AjaxButton>
        </ButtonArea>
      </el-col>
      <el-col :span="8" :offset="0">
        <FormPanel ref="ballanceInfoForm" :list="ballanceInfoFormList" :cols="1" :labelWidth="90" :isSubmitBtn="false"></FormPanel>
      </el-col>
    </el-row>

    <!-- 估价单选择 -->
    <BaseDialog :visible.sync="showEstimateSelectPanel" title="选择估价单" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <estimateSelect @close="showEstimateSelectPanel = false" @onConfirm="handleEstimateSelectConfirm" />
    </BaseDialog>

    <!-- 车辆选择 -->
    <BaseDialog :visible.sync="showVehicleChoicePanel" title="选择车辆" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <vehicleChoice @close="showVehicleChoicePanel = false" @onConfirm="handleVehicleChoiceConfirm" />
    </BaseDialog>

    <!-- 车辆送修人 -->
    <BaseDialog :visible.sync="showLinkManChoicePanel" title="车辆送修人" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <linkManChoice :vin="carVin" :ownerNo="ownerNo" @close="showLinkManChoicePanel = false" @onConfirm="handleLinkManChoiceConfirm" />
    </BaseDialog>

    <!-- 新增维修项目 -->
    <BaseDialog :visible.sync="showAddRepairLabourPanel" title="新增维修项目" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <addRepairLabour :modelId="carModelId" @close="showAddRepairLabourPanel = false" @onConfirm="handleAddRepairLabourConfirm" />
    </BaseDialog>

    <!-- 新增维修配件 -->
    <BaseDialog :visible.sync="showAddRepairPartPanel" title="新增维修配件" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <addRepairPart
        :powerType="carPowerType"
        :repairLabourDict="repairLabourSelectList"
        :chargePartitionDict="sfqfDict"
        :defaultChargePartition="defaultChargePartition"
        :defaultRepairLabour="selectedRepairLabourList"
        @close="showAddRepairPartPanel = false"
        @onConfirm="handleAddRepairPartConfirm"
      />
    </BaseDialog>

    <!-- 编辑维修配件 -->
    <BaseDialog :visible.sync="showEditRepairPartPanel" title="编辑维修配件" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <editRepairPart
        :repairLabourDict="repairLabourSelectList"
        :chargePartitionDict="sfqfDict"
        :editPartData="editPartData"
        :rechargeableCodes="rechargeableCodes"
        @close="showEditRepairPartPanel = false"
        @onConfirm="handleEditPartConfirm"
      />
    </BaseDialog>

    <!-- 新增附加项目 -->
    <BaseDialog :visible.sync="showAddAdditionItemPanel" title="附加项目选择" width="25%" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <addAdditionItem :chargePartitionDict="sfqfDict" :defaultChargePartition="defaultChargePartition" @close="showAddAdditionItemPanel = false" @onConfirm="handleAddAdditionItemConfirm" />
    </BaseDialog>

    <!-- 维修套餐 -->
    <BaseDialog :visible.sync="showRepairSetMealPanel" title="维修套餐信息" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <repairSetMeal
        :powerType="carPowerType"
        :selectedSetMealCodeList="selectedSetMealCodeList"
        :residueSetMealCount="residueSetMealCount"
        @close="showRepairSetMealPanel = false"
        @onConfirm="handleSetMealConfirm"
      />
    </BaseDialog>

    <!-- 估价单打印 -->
    <BasePrint ref="printOrder" :showTopIcon="true" :title="appTypeTitle + '估价单'" :data="orderPrintData" :isPreview="false" template="repair/repairOrder" />

    <!-- 估算结算单打印 -->
    <BasePrint ref="printBallance" :showTopIcon="true" :title="appTypeTitle + '估价结算单'" :data="ballancePrintData" :isPreview="false" template="repair/ballanceOrder" />
  </div>
</template>

<script>
import moment from 'moment';
import dictCode from '@/utils/dictCode';
import { dictionary } from '@/utils/dictMixin';
import { confirmAction, notifyAction, findFormItem, findTableItem, arrayObjDeWeight, setRound, jsonToHump } from '@/utils';
import { getAppId } from '@/assets/js/auth';

import estimateSelect from './estimateSelect';
import editRepairPart from '../customer/editRepairPart';
import vehicleChoice from '../customer/vehicleChoice';
import addRepairLabour from '../customer/addRepairLabour';
import addRepairPart from '../customer/addRepairPart';
import addAdditionItem from '../customer/addAdditionItem';
import linkManChoice from '../customer/linkManChoice';
import repairSetMeal from '../customer/repairSetMeal';

import { searchRoleByCode } from '@/api/common/empSelect/index';
import { getWxlxSelect, getSfqfSelect, getBxgsSelect } from '@/api/repair/repairReception/customer';
import { getPinpSelect, getChexSelect, queryModelBySeriesId } from '@/api/repair/repairReception/customer/brand';
import { getDealerUser, findUserControlStorageCode, findAllRepair } from '@/api/repair/common';
import { queryUserControlDiscountMode1 } from '@/api/repair/repairReception/feesSettlement';
import { saveRepairEstimateOrder, queryRepairEstimateOrderDetail, discardRepairEstimateOrder, printRepairEstimateOrder, printSettlementEstimateOrder } from '@/api/repair/repairReception/evaluation';

export default {
  components: { vehicleChoice, addRepairLabour, addRepairPart, addAdditionItem, linkManChoice, repairSetMeal, estimateSelect, editRepairPart },
  mixins: [dictionary],
  data() {
    this.selectedRepairLabourList = []; // 选中的维修项目列表
    this.selectedRepairPartList = []; // 选中的维修配件列表
    this.selectedAdditionItemList = []; // 选中的附加项目列表
    this.deletedRepairLabourList = []; // 删除的项目列表
    this.deletedRepairPartList = []; // 删除的配件列表
    this.deletedAdditionItemList = []; // 删除的附加项目列表
    this.carPowerType = 60081001; // 车辆动力类型
    this.rechargeableCodes = ['B', 'Z']; // 需要收钱的收费区分（保险，自费）
    this.repairTypeList = []; // 全部维修类型
    this.sfqfDict = []; // 收费区分字典
    this.editPartData = {}; // 编辑中的配件数据
    this.residueSetMealCount = 0; // 套餐包剩余使用次数(套餐包为能够免费使用套餐的次数)
    this.tax = 0.13; // 维修税率
    this.discountModeList = []; // 权限优惠模式列表
    this.discourtHistoryList = [1, 1, 1, 1]; // 折扣历史储存
    // 最低折扣权限
    this.discountLimt = {
      ADDITIONAL_ITEMS_DISCOUNT: 1,
      LABOUR_AMOUNT_DISCOUNT: 1,
      REPAIR_PART_DISCOUNT: 1,
      SALES_PART_DISCOUNT: 1
    };
    this.estimateOrderData = {}; // 估价单数据

    return {
      // 页签
      activeDetailInfoTab: '维修项目', // 激活的明细信息tab

      // 表单
      mainOrderFormList: this.createMainOrderFormList(),
      ballanceFormList: this.createBallanceFormList(),
      ballanceInfoFormList: this.createBallanceInfoFormList(),
      receivableFormList: this.createReceivableFormList(),
      realIncomeFormList: this.createRealIncomeFormList(),
      discountFormList: this.createDiscountFormList(),

      // 表格
      repairLabourColumns: this.createRepairLabourColumns(),
      repairPartColumns: this.createRepairPartColumns(),
      additionItemColumns: this.createAdditionItemColumns(),

      // 弹窗
      showVehicleChoicePanel: false,
      showAddRepairLabourPanel: false,
      showAddRepairPartPanel: false,
      showEditRepairPartPanel: false,
      showAddAdditionItemPanel: false,
      showLinkManChoicePanel: false,
      showRepairSetMealPanel: false,
      showEstimateSelectPanel: false,

      // 页面数据
      pageType: 'default', // 页面当前状态 default edit create show
      pageLoadingSwitch: false, // 页面loading开关
      bottomBtnDisabledObj: {
        // 底部按钮禁用状态
        create: false,
        setMeal: true,
        save: true,
        edit: true,
        cancellation: true,
        exportOrder: true,
        printBallance: true,
        printEvaluation: true
      },
      repairLabourTableDataSource: [], // 维修项目table数据源
      repairPartTableDataSource: [], // 维修配件table数据源
      additionItemTableDataSource: [], // 附加项目table数据源
      syncRepairLabourTableDataList: [], // 同步的维修项目table数据
      syncRepairPartTableDataList: [], // 同步的维修配件table数据
      syncAdditionItemTableDataList: [], // 同步的附加项目table数据
      ownerNo: '', // 车主代码 单独存放用于查询送修人
      carInfo: {}, // 车辆信息 传递给开单
      appTypeTitle: getAppId() == 'beijing' ? '北京汽车' : '蓝谷极狐',
      orderPrintData: {}, // 估价单打印数据
      ballancePrintData: {} // 结算单打印数据
    };
  },
  computed: {
    // table插槽中的按钮禁用状态
    tableBtnDisabled() {
      return this.pageType != 'create' && this.pageType != 'edit';
    },
    // 工单维修类型
    pageRepairTypeCode() {
      return findFormItem(this.mainOrderFormList, 'repairTypeCode').initialValue;
    },
    // 工单维修类型对应的默认收费区分
    defaultChargePartition() {
      return this.getDefaultChargePartitionByType(this.pageRepairTypeCode);
    },
    // 维修项目下拉框(配件选择用)
    repairLabourSelectList() {
      let deweightList = arrayObjDeWeight(this.syncRepairLabourTableDataList, 'LABOUR_CODE');
      return deweightList.map(item => ({ text: item.LABOUR_NAME, value: item.LABOUR_CODE }));
    },
    // 工时单价
    pageLabourPrice() {
      return findFormItem(this.ballanceFormList, 'labourPrice').initialValue;
    },
    // 车辆车型
    carModelId() {
      return findFormItem(this.mainOrderFormList, 'model').initialValue;
    },
    // 车辆vin
    carVin() {
      return findFormItem(this.mainOrderFormList, 'vin').initialValue;
    },
    // 已选的套餐代码（通过项目配件过滤）
    selectedSetMealCodeList() {
      return [...new Set([...this.syncRepairLabourTableDataList.map(item => item.PACKAGE_CODE), ...this.syncRepairPartTableDataList.map(item => item.PACKAGE_CODE)])];
    },
    estimateNo() {
      return findFormItem(this.mainOrderFormList, 'estimateNo').initialValue;
    }
  },
  watch: {
    // 监听页面变化改变禁用状态
    pageType(newVal, oldVal) {
      this.setPageFormDisabledByPageType(newVal);
    },
    // 监听维修项目变化重新赋值维修材料中维修项目名称字典项
    repairLabourSelectList(newVal, oldVal) {
      let tableTarget = findTableItem(this.repairPartColumns, 'LABOUR_CODE');
      tableTarget.editItems = tableTarget.filterItmes = newVal;
    },
    activeDetailInfoTab(newVal, oldVal) {
      this.handleDetailTabChange(newVal);
    }
  },
  mounted() {
    this.initPageBaseParams();
  },
  methods: {
    // 表格表单编辑
    createMainOrderFormList() {
      return [
        {
          type: 'INPUT',
          label: '估价单号',
          fieldName: 'estimateNo',
          readonly: true,
          initialValue: '',
          unitRender: () => {
            return (
              <el-button
                icon="el-icon-search"
                onClick={() => {
                  this.showEstimateSelectPanel = true;
                }}
              />
            );
          }
        },
        {
          type: 'INPUT',
          label: '车牌号',
          fieldName: 'license',
          initialValue: '',
          disabled: true,
          rules: [{ required: true, message: '车牌号不能为空', trigger: 'blur' }],
          unitRender: () => {
            return (
              <el-button
                icon="el-icon-search"
                onClick={() => {
                  this.showVehicleChoicePanel = true;
                }}
              />
            );
          }
        },
        {
          type: 'INPUT',
          label: 'VIN',
          fieldName: 'vin',
          disabled: true,
          rules: [{ required: true, message: 'VIN不能为空', trigger: 'blur' }]
        },
        {
          type: 'INPUT',
          label: '车主',
          fieldName: 'ownerName',
          disabled: true,
          rules: [{ required: true, message: '车主不能为空', trigger: 'blur' }]
        },
        {
          type: 'DATE_TIME',
          label: '开单日期',
          disabled: true,
          initialValue: '',
          fieldName: 'roCreateDate'
        },
        {
          type: 'SELECT',
          label: '维修类型',
          fieldName: 'repairTypeCode',
          placeholder: '请选择...',
          itemList: [],
          initialValue: '',
          disabled: true,
          rules: [{ required: true, message: '请选择维修类型', trigger: 'change' }],
          change: val => {
            this.$nextTick(() => {
              this.handleRepairTypeChange(val);
            });
          }
        },
        {
          type: 'SELECT',
          label: '服务顾问',
          fieldName: 'serviceAdvisor',
          disabled: true,
          initialValue: '',
          itemList: [],
          rules: [{ required: true, message: '请选择服务顾问', trigger: 'change' }]
        },
        {
          type: 'INPUT',
          label: '送修人姓名',
          fieldName: 'deliverer',
          disabled: true,
          rules: [{ required: true, trigger: 'blur', message: '送修人姓名不能为空' }],
          unitRender: () => {
            return (
              <el-button
                icon="el-icon-search"
                onClick={() => {
                  this.showLinkManChoicePanel = true;
                }}
              />
            );
          }
        },
        {
          type: 'SELECT',
          label: '送修人性别',
          fieldName: 'delivererGender',
          disabled: true,
          itemList: this.createDictList('8012'),
          rules: [{ required: true, message: '请选择送修人性别', trigger: 'change' }]
        },
        {
          type: 'INPUT',
          label: '送修人手机',
          fieldName: 'delivererMobile',
          disabled: true,
          maxlength: 11,
          rules: [
            { required: true, message: '送修人手机不能为空', trigger: 'change' },
            {
              pattern: /^[1][0-9][0-9]{9}$/,
              message: '请填写正确的手机格式',
              trigger: 'change'
            }
          ]
        },
        {
          type: 'SELECT',
          label: '品牌',
          fieldName: 'brand',
          disabled: true,
          itemList: [],
          rules: [{ required: true, message: '请选择品牌', trigger: 'change' }],
          change: this.handleBrandChange
        },
        {
          type: 'SELECT',
          label: '车系',
          fieldName: 'series',
          disabled: true,
          itemList: [],
          rules: [{ required: true, message: '请选择车系', trigger: 'change' }],
          change: this.handleSeriesChange
        },
        {
          type: 'SELECT',
          label: '车型',
          fieldName: 'model',
          disabled: true,
          itemList: [],
          rules: [{ required: true, message: '请选择车型', trigger: 'change' }]
        },
        {
          type: 'INPUT_NUMBER',
          label: '行驶里程',
          fieldName: 'inMileage',
          max: Infinity,
          disabled: true,
          rules: [{ required: true, message: '请输入进厂行驶里程', trigger: 'blur' }]
        },
        // {
        //   type: 'DATE_TIME',
        //   label: '结算时间',
        //   disabled: true,
        //   initialValue: '',
        //   fieldName: 'ballanceTime'
        // },
        {
          type: 'DATE_TIME',
          label: '预交车时间',
          fieldName: 'endTimeSupposed',
          hidden: true,
          minDateTime: '',
          disabled: true
        },
        {
          type: 'SELECT',
          label: '燃油量',
          fieldName: 'oilRemain',
          disabled: true,
          itemList: [
            { text: '1/4', value: '1/4' },
            { text: '1/3', value: '1/3' },
            { text: '1/2', value: '1/2' },
            { text: '2/3', value: '2/3' },
            { text: '3/4', value: '3/4' },
            { text: 'FULL', value: 'FULL' }
          ]
        },
        // {
        //   type: 'DATE_TIME',
        //   label: '完工日期',
        //   disabled: true,
        //   initialValue: '',
        //   fieldName: 'itemEndTime'
        // },
        // {
        //   type: 'DATE_TIME',
        //   label: '终检日期',
        //   disabled: true,
        //   initialValue: '',
        //   fieldName: 'completeTime'
        // },
        {
          type: 'INPUT_NUMBER',
          label: '剩余续航里程',
          fieldName: 'remainingMileage',
          disabled: true,
          max: Infinity
        },
        {
          type: 'INPUT',
          label: '检查结果',
          fieldName: 'roTroubleDesc',
          disabled: true,
          placeholder: '请输入...',
          rules: [{ required: true, message: '请填写故障描述', trigger: 'blur' }]
        },
        {
          type: 'INPUT',
          label: '客户描述',
          fieldName: 'customerDesc',
          disabled: true,
          rules: [{ required: true, message: '请填写客户描述', trigger: 'blur' }]
        }
      ];
    },
    createBallanceFormList() {
      return [
        {
          type: 'SELECT',
          label: '优惠模式',
          fieldName: 'discountModeCode',
          disabled: true,
          itemList: [],
          change: this.handleDiscountModeChange
        },
        {
          type: 'SELECT',
          label: '工时单价',
          fieldName: 'labourPrice',
          itemList: [
            { text: 80, value: 80 }, // 油车
            { text: 100, value: 100 }, // 油电混
            { text: 260, value: 260 } // AF电车
          ],
          disabled: true,
          initialValue: 80,
          rules: [{ required: true, message: '请选择工时单价', trigger: 'change' }]
        },
        {
          type: 'INPUT',
          label: '发票编号',
          disabled: true,
          fieldName: 'invoiceNo'
        },
        {
          type: 'SELECT',
          label: '发票类型',
          disabled: true,
          fieldName: 'invoiceTypeCode',
          itemList: this.createDictList(1100)
        },
        {
          type: 'SELECT',
          label: '付款方式',
          disabled: true,
          fieldName: 'payTypeCode',
          itemList: this.createDictList('8044', [80441010]).map(item => ({ text: item.text, value: item.value + '' }))
        }
      ];
    },
    createBallanceInfoFormList() {
      return [
        {
          type: 'INPUT_NUMBER',
          label: '不含税金额',
          fieldName: 'totalAmount',
          disabled: true,
          precision: 2
        },
        {
          type: 'INPUT_NUMBER',
          label: '税额',
          fieldName: 'taxAmount',
          disabled: true,
          precision: 2
        },
        {
          type: 'INPUT_NUMBER',
          label: '结算金额',
          fieldName: 'sumAmount',
          disabled: true,
          min: -Infinity,
          initialValue: 0,
          isControls: false,
          precision: 2
        },
        // {
        //   type: 'INPUT_NUMBER',
        //   label: '去零金额',
        //   fieldName: 'subObbAmount',
        //   initialValue: '0.00',
        //   disabled: true,
        //   precision: 2
        // },
        {
          type: 'INPUT_NUMBER',
          label: '收款金额',
          fieldName: 'receiveAmount',
          precision: 2,
          disabled: true
        }
      ];
    },
    createReceivableFormList() {
      return [
        {
          type: 'INPUT_NUMBER',
          label: '工时费',
          fieldName: 'receiveableLabourFee',
          initialValue: '',
          disabled: true,
          precision: 2
        },
        {
          type: 'INPUT_NUMBER',
          label: '维修材料费',
          fieldName: 'receiveableRepairPartFee',
          initialValue: '',
          disabled: true,
          precision: 2
        },
        {
          type: 'INPUT_NUMBER',
          label: '附加项目费',
          fieldName: 'receiveableAddItemFee',
          initialValue: '',
          disabled: true,
          precision: 2
        }
      ];
    },
    createRealIncomeFormList() {
      return [
        {
          type: 'INPUT_NUMBER',
          label: '工时费',
          fieldName: 'realLabourFee',
          initialValue: '',
          disabled: true,
          precision: 2
        },
        {
          type: 'INPUT_NUMBER',
          label: '维修材料费',
          fieldName: 'realRepairPartFee',
          initialValue: '',
          disabled: true,
          precision: 2
        },
        {
          type: 'INPUT_NUMBER',
          label: '附加项目费',
          fieldName: 'realAddItemFee',
          initialValue: '',
          disabled: true,
          precision: 2
        }
      ];
    },
    createDiscountFormList() {
      return [
        {
          type: 'INPUT_NUMBER',
          label: '折扣率',
          fieldName: 'DISCOUNT',
          disabled: true,
          min: 0,
          max: 1,
          isControls: false,
          initialValue: 1,
          onEnter: val => {
            this.handleDiscountEnter(val);
          }
        }
      ];
    },
    createRepairLabourColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: props => {
            return <span>{props.row.$index + 1}</span>;
          }
        },
        {
          title: '收费区分',
          dataIndex: 'CHARGE_PARTITION_CODE',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: [],
          editable: true,
          defaultEditable: true,
          editType: 'select',
          editItems: []
        },
        {
          title: '项目维修类型',
          dataIndex: 'REPAIR_TYPE_CODE',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          editable: true,
          defaultEditable: true,
          filterItems: [],
          editType: 'select',
          editItems: []
        },
        {
          title: '项目代码',
          dataIndex: 'LABOUR_CODE',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '项目名称',
          dataIndex: 'LABOUR_NAME',
          width: 200,
          sorter: true,
          filter: true,
          filterType: 'input',
          editable: true,
          defaultEditable: true,
          editType: 'input',
          showOverflowTooltip: true
        },
        {
          title: '工时费',
          dataIndex: 'LABOUR_AMOUNT',
          sorter: true,
          filter: true,
          filterType: 'input',
          editable: true,
          defaultEditable: true,
          editType: 'number',
          precision: 2,
          min: 0
        },
        {
          title: '派工工时',
          dataIndex: 'ASSIGN_LABOUR_HOUR',
          sorter: true,
          filter: true,
          filterType: 'number',
          editable: true,
          defaultEditable: true,
          editType: 'number',
          precision: 2,
          min: 0
        },
        {
          title: '收费工时',
          dataIndex: 'STD_LABOUR_HOUR',
          sorter: true,
          filter: true,
          filterType: 'number'
          // editable: true,
          // defaultEditable: true,
          // editType: 'number',
          // precision: 2,
        },
        {
          title: '优惠金额',
          dataIndex: 'DISCOUNT_AMOUNT',
          sorter: true,
          filter: true,
          filterType: 'input',
          precision: 2
        },
        {
          title: '折扣率',
          dataIndex: 'DISCOUNT',
          sorter: true,
          filter: true,
          filterType: 'input',
          editable: false,
          defaultEditable: false,
          editType: 'number',
          precision: 2,
          min: 0,
          max: 1
        },
        {
          title: '实收金额',
          dataIndex: 'REAL_AMOUNT',
          sorter: true,
          filter: true,
          filterType: 'input',
          precision: 2
        },
        {
          title: '工时单价',
          dataIndex: 'LABOUR_PRICE',
          sorter: true,
          filter: true,
          filterType: 'input',
          editable: true,
          defaultEditable: true,
          editType: 'number',
          precision: 2,
          min: 0
        },
        // {
        //   title: '责任技师',
        //   dataIndex: 'TECHNICIAN',
        //   sorter: true,
        //   dictItems: [],
        //   filter: true,
        //   filterType: 'checkbox',
        //   filterItems: [],
        //   showOverflowTooltip: true
        // },
        // {
        //   title: '是否派工',
        //   dataIndex: 'ASSIGN_TAG',
        //   sorter: true,
        //   disabled: true,
        //   editable: true,
        //   defaultEditable: true,
        //   editType: 'checkbox',
        //   editItems: [
        //     { text: '', trueValue: 10041001 },
        //     { text: '', falseValue: 10041002 }
        //   ]
        // },
        // {
        //   title: '是否增项',
        //   dataIndex: 'IS_ADDITION',
        //   sorter: true,
        //   disabled: true,
        //   editable: true,
        //   defaultEditable: true,
        //   editType: 'checkbox',
        //   editItems: [
        //     { text: '', trueValue: 10041001 },
        //     { text: '', falseValue: 10041002 }
        //   ]
        // },
        // {
        //   title: '是否委外',
        //   dataIndex: 'CONSIGN_EXTERIOR',
        //   sorter: true,
        //   editable: true,
        //   defaultEditable: true,
        //   editType: 'checkbox',
        //   editItems: [
        //     { text: '', trueValue: 10041001 },
        //     { text: '', falseValue: 10041002 }
        //   ]
        // },
        // {
        //   title: '是否不修',
        //   dataIndex: 'NEEDLESS_REPAIR',
        //   sorter: true,
        //   editable: true,
        //   defaultEditable: true,
        //   editType: 'checkbox',
        //   editItems: [
        //     { text: '', trueValue: 10041001 },
        //     { text: '', falseValue: 10041002 }
        //   ]
        // },
        // {
        //   title: '不修类型',
        //   dataIndex: 'NEEDLESS_TYPE',
        //   sorter: true,
        //   filter: true,
        //   filterType: 'checkbox',
        //   filterItems: this.createDictList('1018'),
        //   editable: true,
        //   defaultEditable: true,
        //   editType: 'select',
        //   editItems: this.createDictList('1018')
        // },
        // {
        //   title: '不修原因',
        //   dataIndex: 'NEEDLESS_REASON',
        //   sorter: true,
        //   filter: true,
        //   filterType: 'input',
        //   editable: true,
        //   defaultEditable: true,
        //   editType: 'input'
        // },
        // {
        //   title: '活动编号',
        //   dataIndex: 'ACTIVITY_CODE',
        //   sorter: true,
        //   filter: true,
        //   filterType: 'input',
        //   showOverflowTooltip: true
        // },
        {
          title: '备注',
          dataIndex: 'REMARK',
          width: 280,
          sorter: true,
          filter: true,
          filterType: 'input',
          editable: true,
          defaultEditable: true,
          editType: 'input',
          showOverflowTooltip: true
        },
        {
          title: '套餐代码',
          dataIndex: 'PACKAGE_CODE',
          sorter: true,
          filter: true,
          filterType: 'input',
          showOverflowTooltip: true
        }
        // {
        //   title: '是否使用套餐包',
        //   dataIndex: 'IS_USE_SET_MEAL_PACKAGE',
        //   sorter: true,
        //   filter: true,
        //   filterType: 'checkbox',
        //   filterItems: this.createDictList(1004),
        //   dictItems: this.createDictList(1004)
        // }
      ];
    },
    createRepairPartColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: props => {
            return <span>{props.row.$index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'operation',
          width: 150,
          render: props => {
            return (
              <el-button
                type="text"
                disabled={props.row.IS_FINISHED == 10041001 || props.row.IS_USE_SET_MEAL_PACKAGE == 10041001}
                onClick={() => {
                  this.handleEditPart(props.row);
                }}
              >
                编辑
              </el-button>
            );
          }
        },
        // {
        //   title: '是否入账',
        //   dataIndex: 'IS_FINISHED',
        //   sorter: true,
        //   filter: true,
        //   filterType: 'checkbox',
        //   filterItmes: this.createDictList(1004),
        //   dictItems: this.createDictList(1004)
        // },
        {
          title: '维修方式',
          dataIndex: 'REPAIR_WAY',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('8093'),
          editable: true,
          defaultEditable: true,
          editType: 'select',
          editRequired: true,
          editItems: this.createDictList('8093'),
          initialValue: 80931002
        },
        {
          title: '收费区分',
          dataIndex: 'CHARGE_PARTITION_CODE',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: [],
          editable: true,
          defaultEditable: true,
          editItems: [],
          editType: 'select'
        },
        {
          title: '配件代码',
          dataIndex: 'PART_NO',
          sorter: true,
          showOverflowTooltip: true,
          filter: true,
          filterType: 'input'
          // editable: false,
          // defaultEditable: true,
          // editType: 'input'
        },
        {
          title: '配件名称',
          dataIndex: 'PART_NAME',
          sorter: true,
          filter: true,
          filterType: 'input',
          showOverflowTooltip: true
          // editable: false,
          // defaultEditable: true,
          // editType: 'input'
        },
        {
          title: '配件销售单价',
          dataIndex: 'PART_SALES_PRICE',
          sorter: true,
          filter: true,
          filterType: 'number',
          precision: 2
          // editable: true,
          // defaultEditable: true,
          // editType: 'number'
        },
        {
          title: '价格系数',
          dataIndex: 'PRICE_RATE',
          hidden: true,
          sorter: true,
          filter: true,
          filterType: 'number',
          precision: 2,
          editable: true,
          defaultEditable: true,
          editType: 'number',
          min: 0,
          max: 1
        },
        {
          title: '配件销售金额',
          dataIndex: 'PART_SALES_AMOUNT',
          sorter: true,
          filter: true,
          filterType: 'input',
          precision: 2
        },
        {
          title: '实收金额',
          dataIndex: 'REAL_AMOUNT',
          sorter: true,
          filter: true,
          filterType: 'input',
          precision: 2
        },
        {
          title: '主要配件',
          dataIndex: 'IS_MAIN_PART',
          sorter: true,
          editable: true,
          defaultEditable: true,
          editType: 'checkbox',
          editItems: [
            { text: '', trueValue: 10041001 },
            { text: '', falseValue: 10041002 }
          ]
        },
        {
          title: '配件数量',
          dataIndex: 'PART_QUANTITY',
          sorter: true,
          filter: true,
          filterType: 'input',
          editable: true,
          defaultEditable: true,
          editType: 'number'
        },
        {
          title: '维修项目名称',
          dataIndex: 'LABOUR_CODE',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: [],
          editable: true,
          defaultEditable: true,
          editType: 'select',
          editItems: []
        },
        {
          title: '折扣率',
          dataIndex: 'DISCOUNT',
          sorter: true,
          filter: true,
          filterType: 'number',
          editable: false,
          defaultEditable: false,
          editType: 'number',
          precision: 2,
          min: 0,
          max: 1
        },
        {
          title: '优惠金额',
          dataIndex: 'DISCOUNT_AMOUNT',
          sorter: true,
          filter: true,
          filterType: 'input',
          precision: 2
        },
        {
          title: '仓库',
          dataIndex: 'STORAGE_CODE',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: [],
          dictItems: []
        },
        // {
        //   title: '不可打折',
        //   dataIndex: 'IS_DISCOUNT',
        //   sorter: true,
        //   filter: true,
        //   disabled: true,
        //   editItems: [
        //     { text: '', trueValue: '10041001' },
        //     { text: '', falseValue: '10041002' }
        //   ]
        // },
        // {
        //   title: '是否增项',
        //   dataIndex: 'IS_ADDITION',
        //   sorter: true,
        //   editable: true,
        //   defaultEditable: true,
        //   disabled: true,
        //   editType: 'checkbox',
        //   editItems: [
        //     { text: '', trueValue: 10041001 },
        //     { text: '', falseValue: 10041002 }
        //   ]
        // },
        {
          title: '库位代码',
          dataIndex: 'STORAGE_POSITION_CODE',
          sorter: true
        },
        // {
        //   title: '是否不修',
        //   dataIndex: 'NEEDLESS_REPAIR',
        //   sorter: true,
        //   editable: true,
        //   defaultEditable: true,
        //   editType: 'checkbox',
        //   editItems: [
        //     { text: '', trueValue: 10041001 },
        //     { text: '', falseValue: 10041002 }
        //   ]
        // },
        // {
        //   title: '不修类型',
        //   dataIndex: 'NEEDLESS_TYPE',
        //   sorter: true,
        //   filter: true,
        //   filterType: 'checkbox',
        //   filterItems: this.createDictList('1018'),
        //   disabled: false,
        //   editable: true,
        //   defaultEditable: true,
        //   editType: 'select',
        //   editItems: this.createDictList('1018')
        // },
        // {
        //   title: '不修原因',
        //   dataIndex: 'NEEDLESS_REASON',
        //   sorter: true,
        //   filter: true,
        //   filterType: 'input',
        //   disabled: false,
        //   editable: true,
        //   defaultEditable: true,
        //   editType: 'input'
        // },
        {
          title: '流水号',
          dataIndex: 'BATCH_NO',
          sorter: true,
          filter: true,
          filterType: 'input',
          hidden: true,
          showOverflowTooltip: true
        },
        // {
        //   title: '拣料单流水号',
        //   dataIndex: 'OUT_STOCK_NO',
        //   sorter: true,
        //   filter: true,
        //   filterType: 'input',
        //   showOverflowTooltip: true
        // },
        // {
        //   title: '活动编号',
        //   dataIndex: 'ACTIVITY_CODE',
        //   sorter: true,
        //   filter: true,
        //   filterType: 'input',
        //   showOverflowTooltip: true
        // },
        {
          title: '套餐代码',
          dataIndex: 'PACKAGE_CODE',
          sorter: true,
          filter: true,
          filterType: 'input',
          showOverflowTooltip: true
        }
        // {
        //   title: '是否使用套餐包',
        //   dataIndex: 'IS_USE_SET_MEAL_PACKAGE',
        //   sorter: true,
        //   filter: true,
        //   filterType: 'checkbox',
        //   filterItems: this.createDictList(1004),
        //   dictItems: this.createDictList(1004)
        // }
      ];
    },
    createAdditionItemColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 50,
          render: props => {
            return <span>{props.$index + 1}</span>;
          }
        },
        // {
        //   title: '操作',
        //   dataIndex: 'operation',
        //   render: props => {
        //     return <el-button type="text">编辑</el-button>;
        //   }
        // },
        {
          title: '收费区分',
          dataIndex: 'CHARGE_PARTITION_CODE',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: [],
          showOverflowTooltip: true,
          editable: true,
          defaultEditable: true,
          editType: 'select',
          editItems: []
        },
        {
          title: '附加项目代码',
          dataIndex: 'ADD_ITEM_CODE',
          sorter: true,
          filter: true,
          filterType: 'input',
          showOverflowTooltip: true
        },
        {
          title: '附加项目名称',
          dataIndex: 'ADD_ITEM_NAME',
          sorter: true,
          filter: true,
          filterType: 'input',
          showOverflowTooltip: true
        },
        {
          title: '附加项目费',
          dataIndex: 'ADD_ITEM_AMOUNT',
          sorter: true,
          filter: true,
          filterType: 'input',
          showOverflowTooltip: true,
          precision: 2
        },
        {
          title: '折扣率',
          dataIndex: 'DISCOUNT',
          sorter: true,
          filter: true,
          filterType: 'input',
          showOverflowTooltip: true,
          editable: false,
          defaultEditable: false,
          editType: 'number',
          precision: 2,
          min: 0,
          max: 1
        },
        {
          title: '优惠金额',
          dataIndex: 'DISCOUNT_AMOUNT',
          filter: true,
          filterType: 'input',
          sorter: true,
          showOverflowTooltip: true,
          numberFormat: true,
          precision: 2
        },
        {
          title: '实收金额',
          dataIndex: 'REAL_AMOUNT',
          filter: true,
          filterType: 'input',
          sorter: true,
          showOverflowTooltip: true,
          numberFormat: true,
          precision: 2
        },
        {
          title: '备注',
          dataIndex: 'REMARK',
          filter: true,
          filterType: 'input',
          sorter: true,
          showOverflowTooltip: true,
          editable: true,
          defaultEditable: true,
          editType: 'input'
        }
      ];
    },

    /**
     * table事件
     */
    // 同步维修项目table数据
    handleSyncRepairLabourTableData(list) {
      if (this.$refs.repairLabourTable) {
        list.forEach(item => {
          // 根据是否勾选不修开饭不修类型原因字段编辑
          // this.$refs.repairLabourTable.SET_CELL_DISABLED(item, 'NEEDLESS_TYPE', item.NEEDLESS_REPAIR != 10041001);
          // this.$refs.repairLabourTable.SET_CELL_DISABLED(item, 'NEEDLESS_REASON', item.NEEDLESS_REPAIR != 10041001);
          // 套餐包项目禁用所有字段编辑
          if (item.IS_USE_SET_MEAL_PACKAGE == 10041001) {
            this.editableRepairLabourTableDataIndexs.forEach(item2 => {
              this.$refs.repairLabourTable.SET_CELL_DISABLED(item, item2, true);
            });
          }
        });
      }

      this.syncRepairLabourTableDataList = list;
      // this.pageType == 'create_car' && this.calcEndTimeSupposed();
      this.$nextTick(item => {
        this.calcPayPrice();
      });
    },
    // 同步维修配件table数据
    handleSyncRepairPartTableData(list) {
      // 可编辑字段
      if (this.$refs.repairPartTable) {
        list.forEach(item => {
          // 根据是否勾选不修开饭不修类型原因字段编辑
          // this.$refs.repairPartTable.SET_CELL_DISABLED(item, 'NEEDLESS_TYPE', item.NEEDLESS_REPAIR != 10041001);
          // this.$refs.repairPartTable.SET_CELL_DISABLED(item, 'NEEDLESS_REASON', item.NEEDLESS_REPAIR != 10041001);
          // 根据出库状态及是否为套餐包禁用编辑字段
          if (item.IS_FINISHED == 10041001 || item.IS_USE_SET_MEAL_PACKAGE == 10041001) {
            this.editableRepairPartTableDataIndexs.forEach(item2 => {
              this.$refs.repairPartTable.SET_CELL_DISABLED(item, item2, true);
            });
          }
          item.IS_FINISHED == 10041001 && this.$refs.repairPartTable.SET_CELL_DISABLED(item, 'LABOUR_CODE', true); // 已出库的还需要多禁用维修项目字段
        });
      }
      this.syncRepairPartTableDataList = list;
      this.$nextTick(item => {
        this.calcPayPrice();
      });
    },
    // 同步附加项目table数据
    handleSyncAdditionItemTableData(list) {
      this.syncAdditionItemTableDataList = list;
      this.$nextTick(item => {
        this.calcPayPrice();
      });
    },
    // 维修项目行项选择变化
    handleRepairLabourTableSelect(list) {
      this.selectedRepairLabourList = list;
    },
    // 维修配件行项选择变化
    handleRepairPartTableSelect(list) {
      this.selectedRepairPartList = list;
    },
    // 附加项目行项选择变化
    handleAdditionItemTableSelect(list) {
      this.selectedAdditionItemList = list;
    },
    // 维修项目行项内容变化
    handleRepairLabourTableCellChange(data, row) {
      let dataIndex = Object.keys(data)[0].split('|')[1];
      let calcReceiveAmountDataIndexs = ['LABOUR_AMOUNT', 'LABOUR_PRICE', 'DISCOUNT', 'CHARGE_PARTITION_CODE']; // 需要重新计算实收的字段
      switch (dataIndex) {
        case 'DISCOUNT':
          if (row.DISCOUNT < this.discountLimt.LABOUR_AMOUNT_DISCOUNT) {
            notifyAction(`折扣不能小于维修项目最低折扣权限${this.discountLimt.LABOUR_AMOUNT_DISCOUNT}`, 'warning');
            row.DISCOUNT = 1;
          }
          break;
        case 'LABOUR_AMOUNT':
          row.LABOUR_PRICE = row.STD_LABOUR_HOUR ? row.LABOUR_AMOUNT / row.STD_LABOUR_HOUR : 0;
          break;
        case 'LABOUR_PRICE':
          row.LABOUR_AMOUNT = row.STD_LABOUR_HOUR * row.LABOUR_PRICE;
          break;
        // case 'NEEDLESS_REPAIR':
        //   this.$refs.repairLabourTable.SET_CELL_DISABLED(row, 'NEEDLESS_TYPE', row.NEEDLESS_REPAIR != 10041001);
        //   this.$refs.repairLabourTable.SET_CELL_DISABLED(row, 'NEEDLESS_REASON', row.NEEDLESS_REPAIR != 10041001);
        //   row.NEEDLESS_REPAIR == 10041002 && (row.NEEDLESS_TYPE = '');
        //   row.NEEDLESS_REPAIR == 10041002 && (row.NEEDLESS_REASON = '');
        //   break;
      }
      if (calcReceiveAmountDataIndexs.includes(dataIndex)) {
        this.calcRepairLabourReceiveAmount(row);
        this.calcPayPrice();
      }
    },
    // 维修配件行项内容变化
    handleRepairPartTableCellChange(data, row) {
      let dataIndex = Object.keys(data)[0].split('|')[1];
      let calcReceiveAmountDataIndexs = ['CHARGE_PARTITION_CODE', 'PART_QUANTITY', 'NEEDLESS_REPAIR']; // 需要重新计算实收的字段

      switch (dataIndex) {
        case 'PART_QUANTITY':
          row.PART_SALES_AMOUNT = row.PART_SALES_PRICE * (row.PART_QUANTITY || 0);
          break;
        case 'NEEDLESS_REPAIR':
          this.$refs.repairPartTable.SET_CELL_DISABLED(row, 'NEEDLESS_TYPE', row.NEEDLESS_REPAIR != 10041001);
          this.$refs.repairPartTable.SET_CELL_DISABLED(row, 'NEEDLESS_REASON', row.NEEDLESS_REPAIR != 10041001);
          row.NEEDLESS_REPAIR == 10041002 && (row.NEEDLESS_TYPE = '');
          row.NEEDLESS_REPAIR == 10041002 && (row.NEEDLESS_REASON = '');
          break;
      }

      if (calcReceiveAmountDataIndexs.includes(dataIndex)) {
        this.calcRepairPartReceiveAmount(row);
        this.calcPayPrice();
      }
    },
    // 附加项目行项变化
    handleAdditionItemTableCellChange(data, row) {
      let dataIndex = Object.keys(data)[0].split('|')[1];
      let calcReceiveAmountDataIndexs = ['DISCOUNT', 'CHARGE_PARTITION_CODE']; // 需要重新计算实收的字段
      if (dataIndex == 'DISCOUNT') {
        if (row.DISCOUNT < this.discountLimt.ADDITIONAL_ITEMS_DISCOUNT) {
          notifyAction(`折扣不能小于附加项目最低折扣权限${this.discountLimt.ADDITIONAL_ITEMS_DISCOUNT}`, 'warning');
          row.DISCOUNT = 1;
        }
      }
      if (calcReceiveAmountDataIndexs.includes(dataIndex)) {
        this.calcAdditionItemReceiveAmount(row);
        this.calcPayPrice();
      }
    },
    // 详情tab页切换
    handleDetailTabChange(e) {
      switch (e) {
        case '维修项目':
          findFormItem(this.discountFormList, 'DISCOUNT').initialValue = this.discourtHistoryList[0];
          break;
        case '维修材料':
          findFormItem(this.discountFormList, 'DISCOUNT').initialValue = this.discourtHistoryList[1];
          break;
        case '附加项目':
          findFormItem(this.discountFormList, 'DISCOUNT').initialValue = this.discourtHistoryList[2];
          break;
        case '销售材料':
          findFormItem(this.discountFormList, 'DISCOUNT').initialValue = this.discourtHistoryList[3];
          break;
      }
    },
    /**
     * 弹窗相关
     */
    // 点击新增项目
    handleAddRepairLabour() {
      if (!this.pageRepairTypeCode) return notifyAction('请先选择维修类型', 'warning');
      if (!this.carModelId) return notifyAction('请先维护车辆车型', 'warning');
      if (!this.carVin) return notifyAction('请先选择车辆', 'warning');
      this.showAddRepairLabourPanel = true;
    },
    // 点击新增维修配件
    handleAddRepairPart() {
      if (!this.pageRepairTypeCode) return notifyAction('请先选择维修类型', 'warning');
      if (!this.selectedRepairLabourList.length) return notifyAction('请选择配件对应的维修项目', 'warning');
      if (!this.carVin) return notifyAction('请先选择车辆', 'warning');
      this.showAddRepairPartPanel = true;
    },
    // 点击新增附加项目
    handleAddAdditionItem() {
      if (!this.pageRepairTypeCode) return notifyAction('请先选择维修类型', 'warning');
      if (!this.carVin) return notifyAction('请先选择车辆', 'warning');
      this.showAddAdditionItemPanel = true;
    },
    // 点击维修套餐
    handleRepairSetMealBtnClick() {
      this.showRepairSetMealPanel = true;
    },
    // 维修项目选择点击确定
    handleAddRepairLabourConfirm(list) {
      this.insertRepairLabourToTable(list);
    },
    // 维修配件选择点击确定
    handleAddRepairPartConfirm(e) {
      this.insertRepairPartToTable(e);
    },
    // 附加项目选择点击确定
    handleAddAdditionItemConfirm(e) {
      this.insertAdditionItemToTable(e);
    },
    // 维修套餐带回
    handleSetMealConfirm(e) {
      e.labourList.length && this.insertRepairLabourToTable(e.labourList);
      e.partList.length && this.insertRepairPartToTable(e.partList);
    },
    // 维修配件点击编辑
    handleEditPart(row) {
      this.editPartData = row;
      this.showEditRepairPartPanel = true;
    },
    // 车辆选择带出
    handleVehicleChoiceConfirm(e) {
      this.mainOrderFormList.forEach(item => {
        item.initialValue = item.initialValue || e[item.fieldName] || null;
      });
      this.carPowerType = e.powerType; // 车辆动力类型单独存放(用于配件添加的选择)
      this.querySeriesModelDicts(e.brand, e.series); // 初始化车系车型下拉框
      this.setDefaultLabourPriceByAppidAndCarType(); // 设置默认工时单价
      this.ownerNo = e.ownerNo; // 车主代码(用户查询送修人)
      this.carInfo = e; // 车辆数据
      this.showVehicleChoicePanel = false;
    },
    // 送修人选择带出事件
    handleLinkManChoiceConfirm(e) {
      findFormItem(this.mainOrderFormList, 'deliverer').initialValue = e.ownerName;
      findFormItem(this.mainOrderFormList, 'delivererGender').initialValue = e.gender;
      findFormItem(this.mainOrderFormList, 'delivererMobile').initialValue = e.mobile;
      this.showLinkManChoicePanel = false;
    },
    // 编辑维修配件点击确定
    handleEditPartConfirm(e) {
      let targetRow = this.syncRepairPartTableDataList.find(item => item._uid == e._uid);
      Object.assign(targetRow, e);
      this.calcPayPrice();
      this.showEditRepairPartPanel = false;
    },
    // 估价单选择点击确定
    handleEstimateSelectConfirm(data) {
      console.log(data, '估价单选择带出');
      this.queryPageDataByEstimateNo(data[0].ESTIMATE_NO);
    },

    /**
     * 初始化字典等
     */
    initPageBaseParams() {
      this.queryBrandDicts();
      this.queryRepairTypeDict();
      this.querySfqfDict();
      this.queryRepairParams();
      this.queryServiceAdviserList();
      this.queryDiscountModelByRoNo();
    },
    // 查询售后参数
    async queryRepairParams() {
      let res = await findAllRepair();
      if (res.resultCode == 200) {
        this.repairParams = res.data;

        // 储存元整
        sessionStorage.setItem('precision', res.data['8011']);
        sessionStorage.setItem('settlementType', res.data['1009']);

        this.tax = this.repairParams[1003];

        // 根据参数初始化部分页面数据
        this.setInitialValueByParams(this.repairParams);
      }
    },
    // 获取维修类型
    async queryRepairTypeDict() {
      let res = await getWxlxSelect();
      if (res.resultCode == 200) {
        this.repairTypeList = res.data;
        let repairTypeDict = res.data.map(item => ({ text: item.REPAIR_TYPE_NAME, value: item.REPAIR_TYPE_CODE + '' }));
        let laboutTableRepairType = findTableItem(this.repairLabourColumns, 'REPAIR_TYPE_CODE');
        laboutTableRepairType.editItems = laboutTableRepairType.filterItems = findFormItem(this.mainOrderFormList, 'repairTypeCode').itemList = repairTypeDict;
      }
    },
    // 获取收费区分
    async querySfqfDict() {
      let res = await getSfqfSelect();
      if (res.resultCode == 200) {
        let sfqfDict = res.data.map(item => ({ text: item.CHARGE_PARTITION_NAME, value: item.CHARGE_PARTITION_CODE }));
        this.sfqfDict = sfqfDict;
        let labourChargePartition = findTableItem(this.repairLabourColumns, 'CHARGE_PARTITION_CODE');
        let partChargePartition = findTableItem(this.repairPartColumns, 'CHARGE_PARTITION_CODE');
        let addItemPartition = findTableItem(this.additionItemColumns, 'CHARGE_PARTITION_CODE');
        labourChargePartition.editItems = labourChargePartition.filterItems = partChargePartition.editItems = partChargePartition.filterItems = addItemPartition.editItems = addItemPartition.filterItems = sfqfDict;
      }
    },
    // 查询品牌列表
    async queryBrandDicts() {
      let res = await getPinpSelect();
      if (res.resultCode == 200) {
        findFormItem(this.mainOrderFormList, 'brand').itemList = res.data.map(item => ({ text: item.brandName, value: item.brandId + '' }));
      }
    },
    // 根据品牌及车型id初始化品牌车系下拉框
    querySeriesModelDicts(brandId, seriesId) {
      this.querySeriesDictByBrandId(brandId);
      this.queryModelDictsBySeriesId(seriesId);
    },
    // 根据品牌id查询车系
    async querySeriesDictByBrandId(brandId) {
      let res = await getChexSelect(brandId);
      if (res.resultCode == 200) {
        findFormItem(this.mainOrderFormList, 'series').itemList = res.data.map(item => ({ text: item.seriesName, value: item.seriesId + '' }));
      }
    },
    // 根据车系id查询车型
    async queryModelDictsBySeriesId(seriesId) {
      let res = await queryModelBySeriesId({ seriesId });
      if (res.resultCode == 200) {
        findFormItem(this.mainOrderFormList, 'model').itemList = res.data.map(item => ({ text: item.modelName, value: item.modelId + '' }));
      }
    },
    // 获取服务顾问列表
    async queryServiceAdviserList() {
      let serviceConsultant = { role: dictCode.SERVICE_CONSULTANT };
      let res = await searchRoleByCode(serviceConsultant);
      if (res.resultCode == 200) {
        let serviceAdviserDict = res.data.map(item => ({ text: item.employeeName, value: item.userId + '' }));
        findFormItem(this.mainOrderFormList, 'serviceAdvisor').itemList = serviceAdviserDict;
      }
    },
    // 获取优惠模式权限
    async queryDiscountModelByRoNo() {
      let res = await queryUserControlDiscountMode1();
      if (res.resultCode == 200 && res.data && res.data.discountModeList) {
        this.discountModeList = res.data.discountModeList;
        let disCountModeDict = this.discountModeList.map(item => ({ text: item.PREFERENTIAL_TOTAL || item.DISCOUNT_MODE_NAME, value: item.DISCOUNT_MODE_CODE }));
        findFormItem(this.ballanceFormList, 'discountModeCode').itemList = disCountModeDict;
        this.calcMinDiscountFromDiscountMode(this.discountModeList);
      }
    },

    /**
     * 页面函数
     */
    // 大写字段名转驼峰
    arrayObjToHump(data) {
      let copy = _.cloneDeep(data);
      jsonToHump(copy);
      return copy;
    },
    // 点击新增
    handleCreateNewOrderBtnClick() {
      this.pageType = 'create';

      // 设置部分页面数据
      findFormItem(this.mainOrderFormList, 'roCreateDate').initialValue = moment().format('YYYY-MM-DD HH:mm:ss');
    },
    // 点击编辑
    handleEditBtnClick() {
      this.pageType = 'edit';
    },
    // 点击取消
    handleCancelBtnClick() {
      this.clearPageData();
      this.activeDetailInfoTab = '维修项目';
      this.pageType = 'default';
    },
    // 点击作废
    async handleDiscardRepairOrderClick() {
      await confirmAction('此操作将作废估价单且不可找回，是否继续？');
      let res = await discardRepairEstimateOrder({ estimateNo: this.estimateNo });
      if (res.resultCode == 200) {
        notifyAction('作废成功', 'success');
        this.handleCancelBtnClick();
      }
    },
    // 根据服务参数设置部分默认值
    setInitialValueByParams(params) {
      findFormItem(this.ballanceFormList, 'invoiceTypeCode').initialValue = +params[1030];
      findFormItem(this.ballanceFormList, 'payTypeCode').initialValue = params[1121];
    },
    // 清空页面数据
    clearPageData() {
      this.$refs.mainOrderForm.RESET_FORM();
      this.$refs.ballanceInfoForm.RESET_FORM();
      this.$refs.receivableForm.RESET_FORM();
      this.$refs.realIncomeForm.RESET_FORM();
      this.$refs.ballanceInfoForm.RESET_FORM();

      this.repairLabourTableDataSource = [];
      this.repairPartTableDataSource = [];
      this.additionItemTableDataSource = [];
      this.selectedRepairLabourList = [];
      this.selectedRepairPartList = [];
      this.selectedAdditionItemList = [];
      this.deletedRepairLabourList = [];
      this.deletedRepairPartList = [];
      this.deletedAdditionItemList = [];
    },
    // 根据页面类型变化调整页面禁用字段
    setPageFormDisabledByPageType(val) {
      this.setAllBottomBtnDisabled();

      switch (val) {
        case 'create':
          this.setFormAllFieldDisabled(this.mainOrderFormList, false);
          this.setFormAllFieldDisabled(this.ballanceFormList, false);
          this.setFormAllFieldDisabled(this.discountFormList, false);

          this.setFormFieldDisabled(this.mainOrderFormList, ['estimateNo', 'vin', 'ownerName', 'roCreateDate', 'endTimeSupposed'], true);
          this.setFormFieldDisabled(this.ballanceFormList, ['labourPrice'], true);

          this.bottomBtnDisabledObj.setMeal = false;
          this.bottomBtnDisabledObj.save = false;
          break;
        case 'show':
          this.setFormAllFieldDisabled(this.mainOrderFormList, true);
          this.setFormAllFieldDisabled(this.ballanceFormList, true);
          this.setFormAllFieldDisabled(this.discountFormList, true);

          this.bottomBtnDisabledObj.edit = false;
          this.bottomBtnDisabledObj.cancellation = false;
          this.bottomBtnDisabledObj.exportOrder = false;
          this.bottomBtnDisabledObj.printBallance = false;
          this.bottomBtnDisabledObj.printEvaluation = false;
          break;
        case 'edit':
          this.setFormAllFieldDisabled(this.mainOrderFormList, false);
          this.setFormAllFieldDisabled(this.ballanceFormList, false);
          this.setFormAllFieldDisabled(this.discountFormList, false);

          this.setFormFieldDisabled(this.mainOrderFormList, ['estimateNo', 'vin', 'ownerName', 'roCreateDate', 'endTimeSupposed'], true);
          this.setFormFieldDisabled(this.ballanceFormList, ['labourPrice'], true);

          this.bottomBtnDisabledObj.setMeal = false;
          this.bottomBtnDisabledObj.save = false;
          this.bottomBtnDisabledObj.cancellation = false;
          this.bottomBtnDisabledObj.exportOrder = false;
          this.bottomBtnDisabledObj.printBallance = false;
          this.bottomBtnDisabledObj.printEvaluation = false;
          break;
        case 'default':
          this.setFormAllFieldDisabled(this.mainOrderFormList, true);
          this.setFormAllFieldDisabled(this.ballanceFormList, true);
          this.setFormAllFieldDisabled(this.discountFormList, true);

          this.setFormFieldDisabled(this.mainOrderFormList, ['estimateNo'], false);
          this.bottomBtnDisabledObj.create = false;
          break;
      }
    },
    // 设置全部表单禁用状态
    setFormAllFieldDisabled(formList, status) {
      formList.forEach(item => {
        item.disabled = status;
      });
    },
    // 批量设置表单字段禁用状态
    setFormFieldDisabled(formList, fields, status) {
      fields.forEach(item => {
        findFormItem(formList, item).disabled = status;
      });
    },
    // 禁用全部按钮函数
    setAllBottomBtnDisabled() {
      for (let key in this.bottomBtnDisabledObj) {
        this.bottomBtnDisabledObj[key] = true;
      }
    },
    // 品牌选择变化
    handleBrandChange(val) {
      this.$nextTick(async () => {
        let serIesFormItem = findFormItem(this.mainOrderFormList, 'series');
        let modelFormItem = findFormItem(this.mainOrderFormList, 'model');

        serIesFormItem.initialValue = '';
        modelFormItem.initialValue = '';
        modelFormItem.itemList = [];

        this.querySeriesDictByBrandId(val);
      });
    },
    // 车系选择变化
    handleSeriesChange(val) {
      this.$nextTick(async () => {
        let modelFormItem = findFormItem(this.mainOrderFormList, 'model');
        modelFormItem.initialValue = '';
        this.queryModelDictsBySeriesId(val);
      });
    },
    // 根据维修类型code获取默认收费区分
    getDefaultChargePartitionByType(type) {
      let repairTypeRow = this.repairTypeList.find(item => item.REPAIR_TYPE_CODE == type);
      return repairTypeRow ? repairTypeRow.CHARGE_PARTITION_CODE : 'Z';
    },
    // 新增维修项目插入页面
    insertRepairLabourToTable(labourList) {
      // 校验想要插入的列表是否有重复项目，维修项目不能重复添加
      let repetitionLabourCodes = labourList.filter(item => !!this.syncRepairLabourTableDataList.find(item2 => item2.LABOUR_CODE == item.LABOUR_CODE)).map(item => item.LABOUR_CODE);
      repetitionLabourCodes.length && notifyAction(`项目代码为${repetitionLabourCodes.join(',')}的维修项目已存在，不能重复添加。`, 'warning');
      let insertLabourList = labourList.filter(item => !this.syncRepairLabourTableDataList.find(item2 => item2.LABOUR_CODE == item.LABOUR_CODE));

      insertLabourList.forEach(item => {
        item.REPAIR_TYPE_CODE = item.REPAIR_TYPE_CODE || this.pageRepairTypeCode;
        item.LABOUR_PRICE = item.LABOUR_PRICE || this.pageLabourPrice || 0;
        item.CHARGE_PARTITION_CODE = item.CHARGE_PARTITION_CODE || this.getDefaultChargePartitionByType(item.REPAIR_TYPE_CODE);
        item.DISCOUNT = this.discourtHistoryList[0] || 1;
        item.LABOUR_AMOUNT = item.LABOUR_AMOUNT || item.LABOUR_PRICE * item.STD_LABOUR_HOUR;
        item.CONSIGN_EXTERIOR = this.pageRepairTypeCode == 8 ? 10041001 : 10041002;
        item.IS_ADDITION = 10041002;
        this.calcRepairLabourReceiveAmount(item);
      });
      console.log('insertLabourList', insertLabourList);
      this.$refs.repairLabourTable.EXECUTE_INSERT(insertLabourList);
      notifyAction('维修项目插入成功', 'success');
    },
    // 新增维修配件插入页面
    insertRepairPartToTable(partList) {
      partList.forEach(item => {
        item.REPAIR_TYPE_CODE = item.REPAIR_TYPE_CODE || this.pageRepairTypeCode;
        item.CHARGE_PARTITION_CODE = item.CHARGE_PARTITION_CODE || this.getDefaultChargePartitionByType(item.REPAIR_TYPE_CODE);
        item.PART_QUANTITY = item.PART_QUANTITY || 1;
        item.PART_SALES_AMOUNT = item.PART_SALES_PRICE * item.PART_QUANTITY;
        item.PRICE_RATE = item.PRICE_RATE || 1;
        item.REPAIR_WAY = 80931002;
        item.DISCOUNT = this.discourtHistoryList[1];
        item.IS_FINISHED = 10041002;
        item.IS_ADDITION = 10041002;
        this.calcRepairPartReceiveAmount(item);
      });
      console.log('partList', partList);
      this.$refs.repairPartTable.EXECUTE_INSERT(partList);
      notifyAction('维修配件插入成功', 'success');
    },
    // 新增附加项目插入页面
    insertAdditionItemToTable(addItem) {
      addItem.DISCOUNT = this.discourtHistoryList[2];
      this.calcAdditionItemReceiveAmount(addItem);

      this.$refs.additionItemTable.EXECUTE_INSERT([addItem]);
      notifyAction('附加项目插入成功', 'success');
    },
    // 维修项目删除点击
    handleDeleteRepairLabour() {
      if (!this.selectedRepairLabourList.length) return notifyAction('请选择需要删除的维修项目', 'warning');
      // 过滤使用套餐包项目的套餐代码
      let setMealPackageCodes = [...new Set(this.selectedRepairLabourList.filter(item => item.IS_USE_SET_MEAL_PACKAGE == 10041001).map(item => item.PACKAGE_CODE))];

      confirmAction(`此操作将删除选中的维修项目及相关配件，${setMealPackageCodes.length ? '套餐包套餐也将整体删除，' : ''}是否继续`, 'warning')
        .then(() => {
          let deleteLabours = setMealPackageCodes.length ? this.syncRepairLabourTableDataList.filter(item => setMealPackageCodes.includes(item.PACKAGE_CODE)) : this.selectedRepairLabourList; // 要删除的项目
          let labourCodes = deleteLabours.map(item => item.LABOUR_CODE);
          let relevantParts = this.syncRepairPartTableDataList.filter(item => labourCodes.includes(item.LABOUR_CODE) || setMealPackageCodes.includes(item.PACKAGE_CODE)); // 项目相关配件,或者同套餐包的配件

          // 将删除的数据储存到删除的列表中
          deleteLabours.forEach(item => {
            item.ITEM_ID && this.deletedRepairLabourList.push(item);
          });
          relevantParts.forEach(item => {
            item.ITEM_ID && this.deletedRepairPartList.push(item);
          });

          this.$refs.repairLabourTable.EXECUTE_DELETE(deleteLabours);
          this.$refs.repairPartTable.EXECUTE_DELETE(relevantParts);
        })
        .catch(err => {});
    },
    // 维修配件点击删除
    handleDeleteRepairPart() {
      if (!this.selectedRepairPartList.length) return notifyAction('请选择需要删除的维修配件', 'warning');
      // 过滤出套餐包配件的套餐代码
      let setMealPackageCodes = [...new Set(this.selectedRepairPartList.filter(item => item.IS_USE_SET_MEAL_PACKAGE == 10041001).map(item => item.PACKAGE_CODE))];

      confirmAction(`此操作将删除选中的维修配件，${setMealPackageCodes.length ? '套餐包套餐也将整体删除，' : ''}是否继续`, 'warning')
        .then(() => {
          let deleteParts = setMealPackageCodes.length ? this.syncRepairPartTableDataList.filter(item => setMealPackageCodes.includes(item.PACKAGE_CODE)) : this.selectedRepairPartList; // 要删除的项目
          let relevantLabour = this.syncRepairLabourTableDataList.filter(item => setMealPackageCodes.includes(item.PACKAGE_CODE)); // 套餐包关联的项目

          // 将删除的数据储存到删除的列表中
          relevantLabour.forEach(item => {
            item.ITEM_ID && this.deletedRepairLabourList.push(item);
          });
          deleteParts.forEach(item => {
            item.ITEM_ID && this.deletedRepairPartList.push(item);
          });

          this.$refs.repairLabourTable.EXECUTE_DELETE(relevantLabour);
          this.$refs.repairPartTable.EXECUTE_DELETE(deleteParts);
        })
        .catch(err => {});
    },
    // 附加项目点击删除
    handleDeleteAdditionItem() {
      if (!this.selectedAdditionItemList.length) return notifyAction('请选择需要删除的附加项目', 'warning');
      confirmAction('此操作将删除选中的附加项目，是否继续', 'warning')
        .then(() => {
          this.selectedAdditionItemList.forEach(item => {
            item.ITEM_ID && this.deletedAdditionItemList.push(item);
          });
          this.$refs.additionItemTable.EXECUTE_DELETE(this.selectedAdditionItemList);
        })
        .catch(err => {});
    },
    // 页面维修类型改变
    handleRepairTypeChange(e) {
      // 切换为首保类型时需要清空选择的项目及配件
      e == 0 && this.clearTableData();
      // 切换为电池维修时是否委外为默认勾选否则取消
      this.syncRepairLabourTableDataList.forEach(item => {
        item.CONSIGN_EXTERIOR = e == 8 ? 10041001 : 10041002;
      });

      this.$nextTick(() => {
        // 重新赋值项目配件收费区分及维修类型并重新计算（套餐包的配件项目不参与修改）
        this.syncRepairLabourTableDataList.forEach(item => {
          if (item.IS_USE_SET_MEAL_PACKAGE != 10041001) {
            item.REPAIR_TYPE_CODE = e;
            item.CHARGE_PARTITION_CODE = this.defaultChargePartition;
          }
          this.calcRepairLabourReceiveAmount(item);
        });
        this.syncRepairPartTableDataList.forEach(item => {
          if (item.IS_USE_SET_MEAL_PACKAGE != 10041001) {
            item.CHARGE_PARTITION_CODE = this.defaultChargePartition;
          }
          this.calcRepairPartReceiveAmount(item);
        });
        this.syncAdditionItemTableDataList.forEach(item => {
          item.CHARGE_PARTITION_CODE = this.defaultChargePartition;
          this.calcAdditionItemReceiveAmount(item);
        });
        this.calcPayPrice();
      });
    },
    // 过滤优惠模式中各项优惠最小值
    calcMinDiscountFromDiscountMode(modeList) {
      let obj = {
        REPAIR_PART_DISCOUNT: 1,
        LABOUR_AMOUNT_DISCOUNT: 1,
        ADDITIONAL_ITEMS_DISCOUNT: 1,
        SALES_PART_DISCOUNT: 1
      };
      let calcObj = modeList.reduce((t, v) => {
        t.REPAIR_PART_DISCOUNT = v.REPAIR_PART_DISCOUNT < t.REPAIR_PART_DISCOUNT ? v.REPAIR_PART_DISCOUNT : t.REPAIR_PART_DISCOUNT;
        t.LABOUR_AMOUNT_DISCOUNT = v.LABOUR_AMOUNT_DISCOUNT < t.LABOUR_AMOUNT_DISCOUNT ? v.LABOUR_AMOUNT_DISCOUNT : t.LABOUR_AMOUNT_DISCOUNT;
        t.ADDITIONAL_ITEMS_DISCOUNT = v.ADDITIONAL_ITEMS_DISCOUNT < t.ADDITIONAL_ITEMS_DISCOUNT ? v.ADDITIONAL_ITEMS_DISCOUNT : t.ADDITIONAL_ITEMS_DISCOUNT;
        t.SALES_PART_DISCOUNT = v.SALES_PART_DISCOUNT < t.SALES_PART_DISCOUNT ? v.SALES_PART_DISCOUNT : t.SALES_PART_DISCOUNT;
        return t;
      }, obj);

      this.discountLimt = calcObj;
    },
    // 优惠模式变化函数
    handleDiscountModeChange(val) {
      let discountTarget = this.discountModeList.find(item => item.DISCOUNT_MODE_CODE == val);
      // LABOUR_AMOUNT_DISCOUNT ADDITIONAL_ITEMS_DISCOUNT REPAIR_PART_DISCOUNT
      if (discountTarget) {
        this.discourtHistoryList[0] = discountTarget.LABOUR_AMOUNT_DISCOUNT || 1;
        this.discourtHistoryList[1] = discountTarget.REPAIR_PART_DISCOUNT || 1;
        this.discourtHistoryList[2] = discountTarget.ADDITIONAL_ITEMS_DISCOUNT || 1;
      } else {
        this.discourtHistoryList[0] = 1;
        this.discourtHistoryList[1] = 1;
        this.discourtHistoryList[2] = 1;
      }
      switch (this.activeDetailInfoTab) {
        case '维修项目':
          this.discountFormList.find(item => item.fieldName == 'DISCOUNT').initialValue = this.discourtHistoryList[0];
          break;
        case '维修材料':
          this.discountFormList.find(item => item.fieldName == 'DISCOUNT').initialValue = this.discourtHistoryList[1];
          break;
        case '附加项目':
          this.discountFormList.find(item => item.fieldName == 'DISCOUNT').initialValue = this.discourtHistoryList[2];
          break;
      }
      this.calcTableReceiveAmoutnByDiscount(this.discourtHistoryList[0], this.syncRepairLabourTableDataList, 'LABOUR_AMOUNT');
      this.calcTableReceiveAmoutnByDiscount(this.discourtHistoryList[1], this.syncRepairPartTableDataList, 'PART_SALES_AMOUNT');
      this.calcTableReceiveAmoutnByDiscount(this.discourtHistoryList[2], this.syncAdditionItemTableDataList, 'ADD_ITEM_AMOUNT');
      console.log(val, discountTarget);
    },
    // 折扣率回车事件
    handleDiscountEnter(val) {
      console.log(val, this.activeDetailInfoTab);
      if (val > 1 || val < 0) return;
      switch (this.activeDetailInfoTab) {
        case '维修项目':
          if (val < this.discountLimt.LABOUR_AMOUNT_DISCOUNT) return notifyAction(`折扣不能小于维修项目最低折扣权限${this.discountLimt.LABOUR_AMOUNT_DISCOUNT}`, 'warning');
          if (!this.selectedRepairLabourList.length) return notifyAction('请选择需要打折的项目', 'warning');
          this.calcTableReceiveAmoutnByDiscount(val, this.selectedRepairLabourList, 'LABOUR_AMOUNT');
          this.discourtHistoryList[0] = val;
          break;
        case '维修材料':
          if (val < this.discountLimt.REPAIR_PART_DISCOUNT) return notifyAction(`折扣不能小于维修配件最低折扣权限${this.discountLimt.REPAIR_PART_DISCOUNT}`, 'warning');
          if (!this.selectedRepairPartList.length) return notifyAction('请选择需要打折的配件', 'warning');
          this.calcTableReceiveAmoutnByDiscount(val, this.selectedRepairPartList, 'PART_SALES_AMOUNT');
          this.discourtHistoryList[1] = val;
          break;
        case '附加项目':
          if (val < this.discountLimt.ADDITIONAL_ITEMS_DISCOUNT) return notifyAction(`折扣不能小于附加项目最低折扣权限${this.discountLimt.ADDITIONAL_ITEMS_DISCOUNT}`, 'warning');
          if (!this.selectedAdditionItemList.length) return notifyAction('请选择需要打折的项目', 'warning');
          this.calcTableReceiveAmoutnByDiscount(val, this.selectedAdditionItemList, 'ADD_ITEM_AMOUNT');
          this.discourtHistoryList[2] = val;
          break;
        case '销售材料':
          if (val < this.discountLimt.SALES_PART_DISCOUNT) return notifyAction(`折扣不能小于配件销售最低折扣权限${this.discountLimt.SALES_PART_DISCOUNT}`, 'warning');
          if (!this.selectedSalesPartList.length) return notifyAction('请选择需要打折的配件', 'warning');
          this.calcTableReceiveAmoutnByDiscount(val, this.selectedSalesPartList, 'PART_SALES_AMOUNT');
          this.discourtHistoryList[3] = val;
          break;
      }
    },
    /**
     * @description: 根据传入的折扣及列表给项目或者配件打折
     * @param {Number} discount 折扣
     * @param {Array} lists 需要打折的列表
     * @param {String} receiveableAmountField 列表中的应收字段
     * @author: 何兴家
     */
    calcTableReceiveAmoutnByDiscount(discount, lists, receiveableAmountField) {
      lists.forEach(item => {
        if (this.rechargeableCodes.includes(item.CHARGE_PARTITION_CODE)) {
          item.DISCOUNT = discount;
          item.REAL_AMOUNT = item[receiveableAmountField] * item.DISCOUNT;
          item.DISCOUNT_AMOUNT = item[receiveableAmountField] - item.REAL_AMOUNT;
        }
      });

      this.$nextTick(() => {
        lists.length && this.calcPayPrice();
      });
    },
    // 根据收费区分及折扣重新计算维修项目实收及折扣金额
    calcRepairLabourReceiveAmount(row) {
      row.REAL_AMOUNT = row.NEEDLESS_REPAIR == 10041001 ? 0 : this.rechargeableCodes.includes(row.CHARGE_PARTITION_CODE) ? row.LABOUR_AMOUNT * row.DISCOUNT : 0;
      row.DISCOUNT_AMOUNT = row.NEEDLESS_REPAIR == 10041001 ? 0 : this.rechargeableCodes.includes(row.CHARGE_PARTITION_CODE) ? row.LABOUR_AMOUNT - row.LABOUR_AMOUNT * row.DISCOUNT : 0;
    },
    // 根据收费区分重新计算维修配件实收
    calcRepairPartReceiveAmount(row) {
      row.REAL_AMOUNT = row.NEEDLESS_REPAIR == 10041001 ? 0 : this.rechargeableCodes.includes(row.CHARGE_PARTITION_CODE) ? row.PART_SALES_AMOUNT * row.DISCOUNT : 0;
      row.DISCOUNT_AMOUNT = row.NEEDLESS_REPAIR == 10041001 ? 0 : this.rechargeableCodes.includes(row.CHARGE_PARTITION_CODE) ? row.PART_SALES_AMOUNT - row.PART_SALES_AMOUNT * row.DISCOUNT : 0;
    },
    // 根据收费区分及折扣率重新计算附加项目实收
    calcAdditionItemReceiveAmount(row) {
      row.REAL_AMOUNT = this.rechargeableCodes.includes(row.CHARGE_PARTITION_CODE) ? row.ADD_ITEM_AMOUNT * row.DISCOUNT : 0;
      row.DISCOUNT_AMOUNT = this.rechargeableCodes.includes(row.CHARGE_PARTITION_CODE) ? row.ADD_ITEM_AMOUNT - row.ADD_ITEM_AMOUNT * row.DISCOUNT : 0;
    },
    // 计算页面金额
    calcPayPrice() {
      let receivableObj = { receiveableLabourFee: 0, receiveableRepairPartFee: 0, receiveableAddItemFee: 0 }; // 应收
      let realIncomeObj = { realLabourFee: 0, realRepairPartFee: 0, realAddItemFee: 0 }; // 实收

      // 维修项目
      this.syncRepairLabourTableDataList.forEach(item => {
        receivableObj.receiveableLabourFee += +item.LABOUR_AMOUNT;
        realIncomeObj.realLabourFee += +item.REAL_AMOUNT;
      });

      // 维修配件
      this.syncRepairPartTableDataList.forEach(item => {
        receivableObj.receiveableRepairPartFee += +item.PART_SALES_AMOUNT;
        realIncomeObj.realRepairPartFee += +item.REAL_AMOUNT;
      });

      // 附加项目
      this.syncAdditionItemTableDataList.forEach(item => {
        receivableObj.receiveableAddItemFee += item.ADD_ITEM_AMOUNT;
        realIncomeObj.realAddItemFee += +item.REAL_AMOUNT;
      });

      let totalRealIncomeAmount = 0; // 实收总金额
      Object.keys(realIncomeObj).forEach(item => {
        totalRealIncomeAmount += realIncomeObj[item];
      });
      let taxAmount = totalRealIncomeAmount * (this.tax || 0.13); // 税额
      let noTaxAmount = totalRealIncomeAmount - taxAmount; // 不含税金额
      let roundedAmount = setRound(totalRealIncomeAmount); // 元整后的金额
      let yzAmount = totalRealIncomeAmount - roundedAmount; // 元整金额

      // 应收赋值
      this.receivableFormList.forEach(item => {
        item.initialValue = receivableObj[item.fieldName];
      });
      // 实收赋值
      this.realIncomeFormList.forEach(item => {
        item.initialValue = realIncomeObj[item.fieldName];
      });

      // 赋值结算金额表单
      findFormItem(this.ballanceInfoFormList, 'totalAmount').initialValue = noTaxAmount;
      findFormItem(this.ballanceInfoFormList, 'taxAmount').initialValue = taxAmount;
      findFormItem(this.ballanceInfoFormList, 'sumAmount').initialValue = totalRealIncomeAmount;
      // findFormItem(this.ballanceInfoFormList, 'subObbAmount').initialValue = yzAmount;
      findFormItem(this.ballanceInfoFormList, 'receiveAmount').initialValue = roundedAmount;
    },
    // 拼接及校验数据
    async getPageData(type) {
      let mainFormData = await this.$refs.mainOrderForm.GET_FORM_DATA();
      let ballanceFormData = await this.$refs.ballanceForm.GET_FORM_DATA();
      let receivableFormData = await this.$refs.receivableForm.GET_FORM_DATA();
      let realIncomeFormData = await this.$refs.realIncomeForm.GET_FORM_DATA();
      let ballanceInfoFormData = await this.$refs.ballanceInfoForm.GET_FORM_DATA();

      if (mainFormData[0] || ballanceFormData[0] || receivableFormData[0] || realIncomeFormData[0] || ballanceInfoFormData[0]) return Promise.reject('数据校验：表单校验未通过');

      // table数据合法性校验
      if (this.pageType == 'create' && !this.syncRepairLabourTableDataList.length) {
        notifyAction('请至少添加一项维修项目', 'warning');
        return Promise.reject('数据校验：维修项目数量校验未通过');
      }

      let noEmptyLabourCodeflag = true; // 维修配件必须关联某个项目校验
      let zeroCountPartFlag = true; // 是否有数量为0的配件
      this.syncRepairPartTableDataList.forEach(item => {
        !item.LABOUR_CODE && (noEmptyLabourCodeflag = false);
        !+item.PART_QUANTITY && (zeroCountPartFlag = false);
      });
      if (!noEmptyLabourCodeflag) {
        notifyAction('维修配件的对应维修项目不能为空，请维护', 'warning');
        return Promise.reject('数据校验：配件项目关联校验未通过');
      }
      if (!zeroCountPartFlag) {
        notifyAction('维修配件数量不能为0，请重新维护', 'warning');
        return Promise.reject('数据校验：配件数量校验未通过');
      }

      // 将空串转化为null防止后端报错
      this.syncRepairLabourTableDataList.forEach(item => {
        Object.keys(item).forEach(x => {
          item[x] = item[x] === '' ? null : item[x];
        });
      });
      this.syncRepairPartTableDataList.forEach(item => {
        Object.keys(item).forEach(x => {
          item[x] = item[x] === '' ? null : item[x];
        });
      });
      this.syncAdditionItemTableDataList.forEach(item => {
        Object.keys(item).forEach(x => {
          item[x] = item[x] === '' ? null : item[x];
        });
      });

      return {
        ...this.estimateOrderData,
        ...this.carInfo,
        ...mainFormData[1],
        ...ballanceFormData[1],
        ...receivableFormData[1],
        ...realIncomeFormData[1],
        ...ballanceInfoFormData[1],
        labourList: type ? this.syncRepairLabourTableDataList : this.arrayObjToHump(this.syncRepairLabourTableDataList),
        delLabourList: type ? this.deletedRepairLabourList : this.arrayObjToHump(this.deletedRepairLabourList),
        partList: type ? this.syncRepairPartTableDataList : this.arrayObjToHump(this.syncRepairPartTableDataList),
        delPartList: type ? this.deletedRepairPartList : this.arrayObjToHump(this.deletedRepairPartList),
        addList: type ? this.syncAdditionItemTableDataList : this.arrayObjToHump(this.syncAdditionItemTableDataList),
        delAddList: type ? this.deletedAdditionItemList : this.arrayObjToHump(this.deletedAdditionItemList)
      };
    },
    // 根据appid及车辆动力类型设置默认工时单价
    setDefaultLabourPriceByAppidAndCarType() {
      let labourPrice = 80;
      if (getAppId() == 'beijing') {
        labourPrice = this.carPowerType == 60081001 ? 80 : 100;
      } else {
        labourPrice = 260;
      }
      findFormItem(this.ballanceFormList, 'labourPrice').initialValue = labourPrice;
      findFormItem(this.ballanceFormList, 'labourPrice').itemList = [{ text: labourPrice, value: labourPrice }];
    },
    // 根据估价单号查询估价单详情
    async queryPageDataByEstimateNo(estimateNo) {
      this.pageLoadingSwitch = true;
      try {
        let res = await queryRepairEstimateOrderDetail({ estimateNo });
        if (res.resultCode == 200) {
          let resultData = res.data;
          this.carPowerType = resultData.powerType;
          this.querySeriesModelDicts(resultData.brand, resultData.series); // 初始化车系车型下拉框
          this.setDefaultLabourPriceByAppidAndCarType(); // 设置默认工时单价
          this.ownerNo = resultData.ownerNo; // 车主代码(用户查询送修人)
          let discount = 1;
          this.estimateOrderData = resultData;
          let formTarget = [...this.mainOrderFormList, ...this.ballanceFormList, ...this.receivableFormList, ...this.realIncomeFormList, ...this.ballanceInfoFormList, ...this.discountFormList];
          formTarget.forEach(item => {
            item.initialValue = resultData[item.fieldName] || null;
            if (item.fieldName == 'DISCOUNT') {
              item.initialValue = resultData.labourList[0].DISCOUNT || null;
            }
          });
          this.discourtHistoryList[0] = resultData.labourList[0].DISCOUNT || null;
          if (resultData.partList[0]) {
            this.discourtHistoryList[1] = resultData.partList[0].DISCOUNT || null;
          }
          if (resultData.addLabourlist[0]) {
            this.discourtHistoryList[2] = resultData.addLabourlist[0].DISCOUNT || null;
          }
          resultData.labourList.forEach(item => {
            if (this.rechargeableCodes.includes(item.CHARGE_PARTITION_CODE)) {
              item.DISCOUNT_AMOUNT = item['LABOUR_AMOUNT'] - item.REAL_AMOUNT;
            }
          });
          resultData.partList.forEach(item => {
            if (this.rechargeableCodes.includes(item.CHARGE_PARTITION_CODE)) {
              item.DISCOUNT_AMOUNT = item['PART_SALES_AMOUNT'] - item.REAL_AMOUNT;
            }
          });
          resultData.addLabourlist.forEach(item => {
            if (this.rechargeableCodes.includes(item.CHARGE_PARTITION_CODE)) {
              item.DISCOUNT_AMOUNT = item['ADD_ITEM_AMOUNT'] - item.REAL_AMOUNT;
            }
          });
          this.repairLabourTableDataSource = resultData.labourList;
          this.repairPartTableDataSource = resultData.partList;
          this.additionItemTableDataSource = resultData.addLabourlist;

          this.pageType = 'show';
        }
      } catch (err) {
        console.log(err, '获取页面数据失败');
      } finally {
        this.pageLoadingSwitch = false;
      }
    },
    // 点击保存
    async handleSave() {
      try {
        let pageData = await this.getPageData();
        let res = await saveRepairEstimateOrder(pageData);
        if (res.resultCode == 200) {
          notifyAction('保存成功', 'success');
          findFormItem(this.mainOrderFormList, 'estimateNo').initialValue = res.data;
          this.pageType = 'show';
          this.handleCancelBtnClick();
          this.queryPageDataByEstimateNo(res.data);
        }
      } catch (err) {
        console.error(err, '保存报错');
      }
      1;
    },
    // 点击导出工单
    async handleCreateRepairOrder() {
      let pageData = await this.getPageData('order');
      // 手动处理部分数据
      pageData.addLabourlist = pageData.addList;
      pageData.carPowerType = this.carPowerType;
      pageData.checkResult = pageData.roTroubleDesc;
      pageData.estimateBeginTime = moment().format('YYYY-MM-DD HH:mm:ss');
      pageData.labourList.forEach(item => {
        delete item.ITEM_ID;
        if (item.CHARGE_PARTITION_CODE == 'Z' || item.CHARGE_PARTITION_CODE == 'B') {
          item.RECEIVE_AMOUNT = item.LABOUR_AMOUNT;
        } else {
          item.RECEIVE_AMOUNT = 0;
        }
      });
      pageData.partList.forEach(item => {
        delete item.ITEM_ID;
        if (item.CHARGE_PARTITION_CODE == 'Z' || item.CHARGE_PARTITION_CODE == 'B') {
          item.RECEIVE_AMOUNT = item.PART_SALES_AMOUNT;
        } else {
          item.RECEIVE_AMOUNT = 0;
        }
      });
      pageData.addLabourlist.forEach(item => {
        delete item.ITEM_ID;
        if (item.CHARGE_PARTITION_CODE == 'Z' || item.CHARGE_PARTITION_CODE == 'B') {
          item.RECEIVE_AMOUNT = item.ADD_ITEM_AMOUNT;
        } else {
          item.RECEIVE_AMOUNT = 0;
        }
      });

      this.$router.push({
        name: 'repairOrder',
        params: { ...this.estimateOrderData, ...pageData }
      });
    },
    // 打印结算单
    async handlePrintBallance() {
      let res = await printSettlementEstimateOrder({ estimateNo: this.estimateNo });
      if (res.resultCode == 200) {
        this.ballancePrintData = res.data;

        this.ballancePrintData.RO_NO = res.data.ESTIMATE_NO;
        this.$refs.printBallance.EXCUTE_PRINT();
      }
    },
    // 打印工单
    async handlePrintRepairOrder() {
      let res = await printRepairEstimateOrder({ estimateNo: this.estimateNo });
      if (res.resultCode == 200) {
        this.orderPrintData = res.data;

        this.orderPrintData.RO_NO = res.data.ESTIMATE_NO;
        this.$refs.printOrder.EXCUTE_PRINT();
      }
    }
  }
};
</script>
